<template>
  <div class="business-management-container">
    <header class="business-header">
      <div class="header-content">
        <div class="logo">
          <div class="logo-icon">🍽</div>
          <h1>美味餐厅管理系统</h1>
        </div>

        <div class="nav-tabs">
          <div v-for="(tab, index) in tabs" :key="index" class="nav-tab" :class="{ active: currentTab === index }"
            @click="handleTabChange(index)">
            <i :class="tab.icon"></i>
            <span>{{ tab.name }}</span>
          </div>
        </div>

        <div class="user-info">
          <div class="user-avatar">经理</div>
          <div>
            <div>{{ user.name || '张经理' }}</div>
            <div style="font-size: 12px; opacity: 0.8;">管理员</div>
          </div>
        </div>
      </div>
    </header>

    <main class="business-main-content">
      <transition name="fade" mode="out-in">
        <div class="page-content" :key="currentTab">
          <!-- 修改店铺信息页面 -->
          <div v-if="currentTab === 0">
            <h2 class="page-title">
              <i class="el-icon-shop"></i>
              修改店铺信息
            </h2>

            <el-form :model="business" label-width="120px" label-position="left">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="店铺名称">
                    <el-input v-model="business.businessName" placeholder="请输入店铺名称"></el-input>
                  </el-form-item>

                  <el-form-item label="店铺图片">
                    <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false"
                      :on-change="handleAvatarChange" :before-upload="beforeAvatarUpload">
                      <img v-if="business.businessImg" :src="business.businessImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>

                  <el-form-item label="店铺地址">
                    <el-input v-model="business.businessAddress" placeholder="请输入店铺地址"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12">
                  <el-form-item label="起送价">
                    <el-input-number v-model="business.startPrice" :min="0" :step="0.01"
                      :precision="2"></el-input-number>
                  </el-form-item>

                  <el-form-item label="配送价">
                    <el-input-number v-model="business.deliveryPrice" :min="0" :step="0.01"
                      :precision="2"></el-input-number>
                  </el-form-item>

                  <el-form-item label="店铺描述">
                    <el-input type="textarea" :rows="4" v-model="business.businessExplain"
                      placeholder="请输入店铺描述"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item>
                <el-button type="primary" @click="saveBusiness">保存修改</el-button>
                <el-button>取消</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 查看历史订单和简单报表页面 -->
          <div v-if="currentTab === 1">
            <h2 class="page-title">
              <i class="el-icon-data-analysis"></i>
              历史订单与报表
            </h2>

            <div class="stats-cards">
              <div class="stat-card">
                <div class="stat-icon icon-order">
                  <i class="el-icon-tickets"></i>
                </div>
                <div class="stat-info">
                  <h3>累计订单数</h3>
                  <div class="stat-value">
                    {{ totalOrders }}
                  </div>
                  <!-- <div class="stat-change change-positive">
                    <i class="el-icon-top"></i>
                    较昨日 +5%
                  </div> -->
                </div>
              </div>

              <div class="stat-card">
                <div class="stat-icon icon-revenue">
                  <i class="el-icon-money"></i>
                </div>
                <div class="stat-info">
                  <h3>累计收入</h3>
                  <div class="stat-value">¥{{ totalRevenue }}</div>
                  <!-- <div class="stat-change change-positive">
                    <i class="el-icon-top"></i>
                    较上月 +12%
                  </div> -->
                </div>
              </div>

              <div class="stat-card">
                <div class="stat-icon icon-avg">
                  <i class="el-icon-goods"></i>
                </div>
                <div class="stat-info">
                  <h3>平均客单价</h3>
                  <div class="stat-value">¥{{ averageOrderValue }}</div>
                  <!-- <div class="stat-change change-positive">
                    <i class="el-icon-top"></i>
                    较上月 +3%
                  </div> -->
                </div>
              </div>
            </div>

            <div class="card">
              <div class="card-title">
                <i class="el-icon-s-order"></i>
                最近订单
              </div>

              <el-table :data="orders" stripe style="width: 100%">
                <el-table-column prop="id" label="订单号" width="100"></el-table-column>
                <el-table-column label="日期" width="120">
                  <template #default="scope">
                    {{ scope.row.updateTime?.split('.')[0] }}
                  </template>
                </el-table-column>
                <el-table-column prop="customerId" label="顾客" width="120"></el-table-column>
                <el-table-column prop="star" label="评分"></el-table-column>
                <el-table-column prop="orderTotal" label="金额" width="100" align="right"></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'" size="small">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default>
                    <el-button type="text" size="small">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="card">
              <div class="card-title">
                <i class="el-icon-data-line"></i>
                近7日销售趋势
              </div>

              <div class="chart-container">
                <canvas id="salesChart"></canvas>
              </div>
            </div>
          </div>

          <!-- 管理员工页面 -->
          <div v-if="currentTab === 2">
            <h2 class="page-title">
              <i class="el-icon-user-solid"></i>
              员工管理
            </h2>

            <div class="action-buttons">
              <button class="btn-primary" @click="showAddEmployeeDialog = true">
                <i class="el-icon-plus"></i>
                添加员工
              </button>
            </div>

            <div class="employee-grid">
              <div v-for="employee in employees" :key="employee.id" class="employee-card">
                <div class="employee-avatar">
                  {{ employee.lastName == null ? "无" : employee.lastName }}
                </div>
                <h3 class="employee-name">{{ employee.firstName == null ? "无" : employee.firstName }}</h3>
                <div class="employee-contact">
                  <i class="el-icon-phone"></i> {{ employee.phone == null ? 0 : employee.phone }}
                </div>
                <!-- <div class="employee-contact">
                  <i class="el-icon-date"></i> 入职: {{ employee.joinDate }}
                </div> -->
                <el-button type="danger" size="small" @click="removeEmployee(employee.id)">
                  <i class="el-icon-close"></i>
                  开除
                </el-button>
              </div>
            </div>

            <!-- 添加员工对话框 -->
            <el-dialog v-model="showAddEmployeeDialog" title="添加员工" width="90%" :style="{ maxWidth: '500px' }"
              class="responsive-dialog">
              <el-form :model="newEmployee" label-width="80px">
                <el-form-item label="id">
                  <el-input v-model="newEmployee.id" placeholder="请输入员工id"></el-input>
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="showAddEmployeeDialog = false">取消</el-button>
                  <el-button type="primary" @click="addEmployee">添加员工</el-button>
                </span>
              </template>
            </el-dialog>
          </div>

          <!-- 修改菜单页面 -->
          <div v-if="currentTab === 3">
            <h2 class="page-title">
              <i class="el-icon-notebook"></i>
              菜单管理
            </h2>

            <div class="action-buttons">
              <button class="btn-primary" @click="addNewDish">
                <i class="el-icon-plus"></i>
                添加菜品
              </button>
            </div>

            <div class="menu-grid">
              <div v-for="dish in filteredMenu" :key="dish.id" class="menu-item">
                <div class="menu-item-img">
                  {{ dish.foodName }}
                </div>
                <div class="menu-item-content">
                  <h3 class="menu-item-title">{{ dish.foodName }}</h3>
                  <!-- 新增食物状态显示 -->
                  <div class="menu-item-status" :class="getStatusClass(dish.status)">
                    {{ getStatusText(dish.status) }}
                  </div>
                  <p class="menu-item-desc">{{ dish.foodExplain }}</p>
                  <div class="menu-item-footer">
                    <div class="menu-item-price">¥{{ dish.foodPrice }}</div>
                    <div>
                      <el-button size="mini" @click="editDish(dish)">编辑</el-button>
                      <!-- 新增售卖状态切换按钮 -->
                      <el-button size="mini" :type="dish.status === 'available' ? 'warning' : 'success'"
                        @click="toggleDishStatus(dish)"
                        v-if="dish.status !== 'Reviewing' && dish.status !== 'rejected'">
                        {{ dish.status === 'available' ? '下线' : '上线' }}
                      </el-button>
                      <el-button size="mini" type="danger" @click="removeDish(dish.id)">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 添加/编辑菜品对话框 -->
            <el-dialog v-model="showAddDishDialog" :title="isEditing ? '编辑菜品' : '添加菜品'" width="90%"
              :style="{ maxWidth: '600px' }" class="responsive-dialog">
              <el-form :model="currentDish" label-width="80px">

                <el-form-item label="菜品图片">
                  <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false"
                    :on-change="handleFoodImgChange" :before-upload="beforeAvatarUpload">
                    <img v-if="currentDish.foodImg" :src="currentDish.foodImg" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>

                <el-form-item label="菜品名称">
                  <el-input v-model="currentDish.foodName" placeholder="请输入菜品名称"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                  <el-input v-model="currentDish.foodExplain" type="textarea" :rows="3"
                    placeholder="请输入菜品描述"></el-input>
                </el-form-item>
                <el-form-item label="价格">
                  <el-input-number v-model="currentDish.foodPrice" :step="0.01"> </el-input-number>
                </el-form-item>

              </el-form>
              <template template #footer>
                <span class=" dialog-footer">
                  <el-button @click="showAddDishDialog = false">取消</el-button>
                  <el-button type="primary" @click="saveDish">保存</el-button>
                </span>
              </template>
            </el-dialog>
          </div>

          <!-- 退出系统 -->
          <div v-if="currentTab === 4">
            <div class="logout-section" >
              <button class="logout-button" @click="logout">
                <i class="fas fa-sign-out-alt"></i>
                确认退出系统
              </button>
            </div>
          </div>
        </div>
      </transition>
    </main>

    <footer class="business-footer">
      <p>© 2025 TJU软工综合实践24组管理系统 | v1.0</p>
    </footer>
  </div>

</template>

<script>

import { ref, reactive, onMounted, nextTick, getCurrentInstance, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'BusinessManagement',
  setup() {
    const { proxy } = getCurrentInstance()
    const router = useRouter()
    const route = useRoute()

    // 响应式数据
    const id = ref(route.query.businessId)
    const token = ref(localStorage.getItem('token'))
    const user = ref({})
    const business = reactive({})
    const orders = ref([])
    const menu = ref([])
    const employees = ref([])

    // 表单数据
    const newEmployee = reactive({
      id: ''
    })

    const currentDish = reactive({
      id: null,
      foodName: '',
      foodExplain: '',
      foodPrice: 0
    })

    const filteredMenu = computed(() => {
      return menu.value.filter(dish =>
        dish.status?.toLowerCase() !== 'deleted'
      )
    })

    // UI状态
    const currentTab = ref(0)
    const showAddEmployeeDialog = ref(false)
    const showAddDishDialog = ref(false)
    const isEditing = ref(false)

    const tabs = [
      { name: '店铺信息', icon: 'el-icon-shop' },
      { name: '订单报表', icon: 'el-icon-data-analysis' },
      { name: '员工管理', icon: 'el-icon-user-solid' },
      { name: '菜单管理', icon: 'el-icon-notebook' },
      { name: '退出系统', icon: 'el-icon-back' }
    ]



    // 计算属性
    const totalRevenue = computed(() => {
      return orders.value.reduce((total, order) => total + (parseFloat(order.orderTotal) || 0), 0).toFixed(2)
    })

    const averageOrderValue = computed(() => {
      // 先确保 orders.value 是数组
      const orderList = Array.isArray(orders.value) ? orders.value : []
      const count = orderList.length

      if (count === 0) {
        return '0.00'
      }

      const revenue = parseFloat(totalRevenue.value)
      return (revenue / count).toFixed(2)
    })

    // 图表实例
    let salesChart = null

    // 初始化数据
    const initData = async () => {
      try {
        // 获取用户信息
        const userResponse = await proxy.$axios.get('/user', {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        user.value = userResponse.data.data

        // 获取商家信息
        const businessResponse = await proxy.$axios.get(`businesses/${id.value}`, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        Object.assign(business, businessResponse.data.data)

        // 获取菜单
        await getMenu()

        // 获取订单
        const ordersResponse = await proxy.$axios.get(`/orders/${id.value}/business`, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        // initData 中
        // 只保留status为'ended'的订单
        const filteredOrders = Array.isArray(ordersResponse.data.data)
          ? ordersResponse.data.data.filter(order => order.status === 'ended')
          : []
        orders.value = Array.isArray(filteredOrders) ? filteredOrders : []

        // 获取员工
        const staffResponse = await proxy.$axios.get(`/staff/${id.value}`, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        employees.value = staffResponse.data.data
      } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('数据加载失败')
      }
    }

    // 获取菜单
    const getMenu = async () => {
      try {
        const response = await proxy.$axios.get(`foods/${id.value}/businessId`, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        menu.value = response.data.data
      } catch (error) {
        console.error('获取菜单失败:', error)
        ElMessage.error('菜单加载失败')
      }
    }

    // 保存店铺信息
    const saveBusiness = async () => {
      try {
        if (user.value.status == 'USER') {
          console.error('权限不够:', error)
          ElMessage.error('权限不够')
        } else {
          await proxy.$axios.put(`businesses/${id.value}/update`, {
            "businessName": business.businessName,
            "businessAddress": business.businessAddress,
            "businessExplain": business.businessExplain,
            "businessImg": business.businessImg,
            "orderTypeId": business.orderTypeId,
            "startPrice": business.startPrice,
            "deliveryPrice": business.deliveryPrice,
            "remarks": business.remarks
          }, {
            headers: { 'Authorization': `Bearer ${token.value}` }
          })
          await getMenu()
          ElMessage.success('店铺信息已保存')
          router.push('/mine')
        }
      } catch (error) {
        console.error('保存店铺信息失败:', error)
        ElMessage.error('保存失败')
      }
    }

    // 添加员工
    const addEmployee = async () => {
      if (!newEmployee.id) {
        ElMessage.warning('请填写完整信息')
        return
      }

      try {
        if (user.value.status == 'USER') {
          console.error('权限不够:', error)
          ElMessage.error('权限不够')
        } else {
          await proxy.$axios.post(`staff/${newEmployee.id}/${id.value}`, {}, {
            headers: { 'Authorization': `Bearer ${token.value}` }
          })
          showAddEmployeeDialog.value = false
          ElMessage.success('员工添加成功')

        }
        // 重新加载员工列表
        const response = await proxy.$axios.get(`/staff/${id.value}`, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        employees.value = response.data.data
        // 重置表单
        newEmployee.id = ''
      } catch (error) {
        console.error('添加员工失败:', error)
        ElMessage.error('添加失败')
      }
    }

    // 删除员工
    const removeEmployee = async (employeeId) => {
      try {
        if (user.value.status == 'USER') {
          console.error('权限不够:', error)
          ElMessage.error('权限不够')
        } else {
          await ElMessageBox.confirm('确定要开除该员工吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          await proxy.$axios.delete(`staff/${employeeId}/${id.value}`, {
            headers: { 'Authorization': `Bearer ${token.value}` }
          })
          showAddEmployeeDialog.value = false
          ElMessage.success('员工已开除')

        }

        // 重新加载员工列表
        const response = await proxy.$axios.get(`/staff/${id.value}`, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })
        employees.value = response.data.data

      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除员工失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }



    // 添加菜品
    const addNewDish = () => {
      isEditing.value = false
      resetDishForm()
      showAddDishDialog.value = true
    }

    // 编辑菜品
    const editDish = (dish) => {
      isEditing.value = true
      Object.assign(currentDish, { ...dish })
      showAddDishDialog.value = true
    }

    // 保存菜品
    const saveDish = async () => {
      if (!currentDish.foodName || currentDish.foodPrice <= 0) {
        ElMessage.warning('请填写菜品名称和价格')
        return
      }

      try {
        if (isEditing.value) {
          // 更新菜品

          if (user.value.status == 'User') {
            console.error('权限不够:', error)
            ElMessage.error('权限不够')
          } else {
            await proxy.$axios.put(`foods`, {
              "id": currentDish.id,
              "foodName": currentDish.foodName,
              "foodExplain": currentDish.foodExplain,
              "foodImg": currentDish.foodImg,
              "foodPrice": currentDish.foodPrice,
              "remarks": currentDish.remarks
            }, {
              headers: { 'Authorization': `Bearer ${token.value}` }
            })
            ElMessage.success('菜品已更新')
          }
        } else {
          // 添加菜品
          if (user.value.status == 'User') {
            console.error('权限不够:', error)
            ElMessage.error('权限不够')
          } else {
            await proxy.$axios.post(`foods`, {
              "foodName": currentDish.foodName,
              "foodExplain": currentDish.foodExplain,
              "foodImg": currentDish.foodImg,
              "foodPrice": currentDish.foodPrice,
              "business": {
                "id": id.value
              },
              "remarks": currentDish.remarks
            }, {
              headers: { 'Authorization': `Bearer ${token.value}` }
            })
            ElMessage.success('菜品已添加')
          }
        }

        showAddDishDialog.value = false
        resetDishForm()
        await getMenu() // 重新加载菜单
      } catch (error) {
        console.error('保存菜品失败:', error)
        ElMessage.error('保存失败')
      }
    }

    // 删除菜品
    const removeDish = async (dishId) => {
      try {
        await ElMessageBox.confirm('确定要删除该菜品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        if (user.value.status == 'User') {
          console.error('权限不够:', error)
          ElMessage.error('权限不够')
        } else {
          await proxy.$axios.put(`/foods/status/${dishId}/Deleted`, {}, {
            headers: { 'Authorization': `Bearer ${token.value}` }
          })
          await getMenu()
          ElMessage.success('菜品已删除')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除菜品失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }




    // 重置菜品表单
    const resetDishForm = () => {
      Object.assign(currentDish, {
        id: null,
        foodName: '',
        foodExplain: '',
        foodPrice: 0
      })
    }

    // 退出系统
    const logout = () => {
      ElMessageBox.confirm('确定要退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/mine')
      }).catch(() => {
        // 取消操作
      })
    }



    // 初始化图表
    const initChart = () => {
      const ctx = document.getElementById('salesChart')
      if (!ctx) return

      if (salesChart) {
        salesChart.destroy()
      }

      // 这里需要引入Chart.js，假设已经全局引入
      if (typeof Chart !== 'undefined') {
        salesChart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: ['6月5日', '6月6日', '6月7日', '6月8日', '6月9日', '6月10日', '6月11日'],
            datasets: [{
              label: '日销售额 (元)',
              data: [3200, 3500, 4200, 3800, 4500, 4800, 5100],
              borderColor: '#409EFF',
              backgroundColor: 'rgba(64, 158, 255, 0.1)',
              tension: 0.3,
              fill: true
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              title: {
                display: true,
                text: '近7日销售趋势'
              }
            },
            scales: {
              y: {
                beginAtZero: true,
                grid: {
                  color: 'rgba(0, 0, 0, 0.05)'
                }
              },
              x: {
                grid: {
                  display: false
                }
              }
            }
          }
        })
      }
    }


    const totalOrders = computed(() => {
      // 确保 orders.value 是数组
      const orderList = Array.isArray(orders.value) ? orders.value : []
      return orderList.length
    })

    const handleFoodImgChange = (uploadFile) => {
      const file = uploadFile.raw;
      if (!file) return;

      // 验证图片格式和大小
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!');
        return;
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return;
      }

      // 读取文件为Base64
      const reader = new FileReader();
      reader.onload = (e) => {
        currentDish.foodImg = e.target.result;
        ElMessage.success('图片已选择（仅前端预览）');
      };
      reader.readAsDataURL(file);
    };
    // 处理图片选择（不上传，仅前端预览）
    const handleAvatarChange = (uploadFile) => {
      const file = uploadFile.raw;
      if (!file) return;

      // 验证图片格式和大小
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!');
        return;
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return;
      }

      // 读取文件为Base64
      const reader = new FileReader();
      reader.onload = (e) => {
        business.businessImg = e.target.result;
        ElMessage.success('图片已选择（仅前端预览）');
      };
      reader.readAsDataURL(file);
    };

    // 仅做前端验证（不实际上传）
    const beforeAvatarUpload = (file) => {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'available': '在售',
        'Reviewing': '审核中',
        'rejected': '审核未通过',
        'soldout': '售完'
      }
      return statusMap[status] || '未知状态'
    }

    // 获取状态样式类
    const getStatusClass = (status) => {
      const classMap = {
        'available': 'status-available',
        'Reviewing': 'status-reviewing',
        'rejected': 'status-rejected',
        'soldout': 'status-soldout'
      }
      return classMap[status] || 'status-unknown'
    }

    // 切换菜品售卖状态
    const toggleDishStatus = async (dish) => {
      try {
        if (user.value.status == 'User') {
          ElMessage.error('权限不够')
          return
        }
        if (dish.status == 'Reviewing' || dish.status == 'rejected') {
          ElMessage.error('审核未通过')
          return
        }

        const newStatus = dish.status === 'available' ? 'soldout' : 'available'
        const actionText = newStatus === 'available' ? '上线' : '下线'

        await ElMessageBox.confirm(`确定要${actionText}该菜品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await proxy.$axios.put(`/foods/status/${dish.id}/${newStatus}`, {}, {
          headers: { 'Authorization': `Bearer ${token.value}` }
        })

        // 更新本地状态
        dish.status = newStatus
        ElMessage.success(`菜品已${actionText}`)
      } catch (error) {
        if (error !== 'cancel') {
          console.error('切换菜品状态失败:', error)
          ElMessage.error('操作失败')
        }
      }
    }


    // 处理tab切换
    const handleTabChange = (index) => {
      currentTab.value = index
      if (index === 1) {
        nextTick(() => {
          setTimeout(initChart, 100)
        })
      }
    }

    // 生命周期
    onMounted(() => {
      initData()

      nextTick(() => {
        initChart()
      })
    })

    return {
      // 响应式数据
      id,
      token,
      user,
      business,
      orders,
      menu,
      employees,
      newEmployee,
      currentDish,

      // UI状态
      currentTab,
      tabs,
      showAddEmployeeDialog,
      showAddDishDialog,
      isEditing,

      // 计算属性
      totalRevenue,
      averageOrderValue,
      filteredMenu,
      totalOrders,

      // 方法
      saveBusiness,
      addEmployee,
      removeEmployee,
      addNewDish,
      editDish,
      saveDish,
      removeDish,
      logout,
      handleTabChange,
      getMenu,
      handleAvatarChange,
      beforeAvatarUpload,
      getStatusText,
      getStatusClass,
      toggleDishStatus,
      handleFoodImgChange
    }
  }
}
</script>



<style scoped>
/* 业务管理系统专用样式 */
.business-management-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.business-header {
  background: linear-gradient(135deg, #409EFF, #79bbff);
  color: white;
  padding: 16px 5%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}

.business-main-content {
  flex: 1;
  padding: 20px 5%;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.business-footer {
  text-align: center;
  padding: 16px;
  background: white;
  color: #909399;
  margin-top: auto;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  font-size: 13px;
}

/* 业务管理系统内部样式 */
.business-management-container .header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.business-management-container .logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.business-management-container .logo-icon {
  font-size: 24px;
  background: white;
  color: #409EFF;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.business-management-container .logo h1 {
  font-size: 20px;
  font-weight: 600;
  white-space: nowrap;
}

.business-management-container .nav-tabs {
  display: flex;
  gap: 4px;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px;
  border-radius: 50px;
  flex-wrap: wrap;
}

.business-management-container .nav-tab {
  padding: 8px 16px;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  white-space: nowrap;
}

.business-management-container .nav-tab:hover {
  background: rgba(255, 255, 255, 0.2);
}

.business-management-container .nav-tab.active {
  background: white;
  color: #409EFF;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.business-management-container .user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.business-management-container .user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: white;
  color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.business-management-container .page-content {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  min-height: 500px;
  transition: all 0.3s ease;
}

.business-management-container .page-title {
  color: #409EFF;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #a0cfff;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
}

.business-management-container .stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.business-management-container .stat-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
}

.business-management-container .stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.business-management-container .stat-icon {
  width: 54px;
  height: 54px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.business-management-container .icon-order {
  background: linear-gradient(45deg, #909399, #a5b4fc);
}

.business-management-container .icon-revenue {
  background: linear-gradient(45deg, #67c23a, #80e5a2);
}

.business-management-container .icon-avg {
  background: linear-gradient(45deg, #e6a23c, #ffc97a);
}

.business-management-container .icon-customer {
  background: linear-gradient(45deg, #f56c6c, #ff9d9d);
}

.business-management-container .stat-info h3 {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
}

.business-management-container .stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.business-management-container .stat-change {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.business-management-container .change-positive {
  color: #67c23a;
}

.business-management-container .card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.business-management-container .card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.business-management-container .menu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
}

.business-management-container .menu-item {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.business-management-container .menu-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.business-management-container .menu-item-img {
  height: 150px;
  background: linear-gradient(45deg, #a0cfff, #79bbff);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
}

.business-management-container .menu-item-content {
  padding: 12px;
}

.business-management-container .menu-item-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 6px;
  color: #333;
}

.business-management-container .menu-item-desc {
  color: #909399;
  font-size: 13px;
  margin-bottom: 12px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.business-management-container .menu-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.business-management-container .menu-item-price {
  font-weight: bold;
  color: #409EFF;
  font-size: 16px;
}

.business-management-container .employee-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
}

.business-management-container .employee-card {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  transition: all 0.3s ease;
}

.business-management-container .employee-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.business-management-container .employee-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin: 0 auto 12px;
  background: linear-gradient(45deg, #a0cfff, #79bbff);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 26px;
  font-weight: bold;
}

.business-management-container .employee-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.business-management-container .employee-contact {
  color: #909399;
  margin-bottom: 12px;
  font-size: 13px;
}

.business-management-container .chart-container {
  height: 320px;
  margin-top: 20px;
  position: relative;
}

.business-management-container .action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.business-management-container .btn-primary {
  background: #409EFF;
  border: none;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
  font-size: 14px;
}

.business-management-container .btn-primary:hover {
  background: #79bbff;
}

.business-management-container .logout-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 30px 0;
}

.business-management-container .logout-button {
  background: linear-gradient(135deg, #ff416c, #ff4b2b);
  color: white;
  border: none;
  border-radius: 50px;
  padding: 18px 45px;
  font-size: 1.5rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.4s ease;
  box-shadow: 0 8px 20px rgba(255, 75, 43, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  position: relative;
  overflow: hidden;
}

.business-management-container .logout-button:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 25px rgba(255, 75, 43, 0.6);
}

.business-management-container .warning-icon {
  background-color: rgba(255, 255, 255, 0.3);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 25px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 75, 43, 0.7);
  }

  70% {
    transform: scale(1.05);
    box-shadow: 0 0 0 15px rgba(255, 75, 43, 0);
  }

  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 75, 43, 0);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .business-main-content {
    padding: 16px 4%;
  }
}

@media (max-width: 992px) {
  .business-management-container .header-content {
    flex-direction: row;
    justify-content: space-between;
  }

  .business-management-container .nav-tabs {
    order: 0;
    width: auto;
    margin: 10px 0;
  }

  .business-management-container .logo {
    order: 1;
  }

  .business-management-container .user-info {
    order: 2;
  }
}

@media (max-width: 768px) {
  .business-header {
    padding: 12px 4%;
  }

  .business-main-content {
    padding: 12px 3%;
  }

  .business-management-container .page-content {
    padding: 16px;
  }

  .business-management-container .stats-cards {
    grid-template-columns: 1fr;
  }

  .business-management-container .menu-grid,
  .business-management-container .employee-grid {
    grid-template-columns: 1fr;
  }

  .business-management-container .nav-tabs {
    width: 100%;
    order: 3;
    margin-top: 10px;
    overflow-x: auto;
    padding-bottom: 5px;
  }

  .business-management-container .header-content {
    flex-wrap: wrap;
  }

  .business-management-container .logo h1 {
    font-size: 18px;
  }

  .business-management-container .chart-container {
    height: 280px;
  }
}

@media (max-width: 576px) {
  .business-management-container .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .business-management-container .nav-tabs {
    width: 100%;
    justify-content: flex-start;
  }

  .business-management-container .user-info {
    align-self: flex-end;
    margin-top: -50px;
  }

  .business-management-container .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .business-management-container .action-buttons>* {
    flex: 1;
    justify-content: center;
  }

  .business-management-container .el-dialog {
    width: 90% !important;
    max-width: 100%;
  }
}

/* 动画效果 */
.business-management-container .fade-enter-active,
.business-management-container .fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.business-management-container .fade-enter-from,
.business-management-container .fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.business-management-container .menu-item-status {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 8px;
}

.business-management-container .status-available {
  background-color: #f0f9ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.business-management-container .status-reviewing {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.business-management-container .status-rejected {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.business-management-container .status-soldout {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.business-management-container .status-unknown {
  background-color: #fafafa;
  color: #8c8c8c;
  border: 1px solid #d9d9d9;
}

/* 响应式弹窗样式 */
.responsive-dialog .el-dialog {
  width: 90% !important;
  max-width: 600px;
  margin: 5vh auto !important;
}

.responsive-dialog .el-dialog__body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .responsive-dialog .el-dialog {
    width: 95% !important;
    margin: 2vh auto !important;
    max-width: none;
  }

  .responsive-dialog .el-dialog__body {
    padding: 15px;
    max-height: 80vh;
  }

  /* 表单在小屏幕上的适配 */
  .responsive-dialog .el-form-item {
    margin-bottom: 16px;
  }

  .responsive-dialog .el-form-item__label {
    font-size: 14px;
    line-height: 1.4;
  }

  .responsive-dialog .el-input,
  .responsive-dialog .el-textarea {
    font-size: 14px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .responsive-dialog .el-dialog {
    width: 98% !important;
    margin: 1vh auto !important;
  }

  .responsive-dialog .el-dialog__header {
    padding: 15px 15px 10px;
  }

  .responsive-dialog .el-dialog__body {
    padding: 10px 15px;
  }

  .responsive-dialog .el-dialog__footer {
    padding: 10px 15px 15px;
  }

  /* 按钮组在小屏幕上垂直排列 */
  .responsive-dialog .dialog-footer {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .responsive-dialog .dialog-footer .el-button {
    width: 100%;
    margin: 0;
  }
}

/* 图片上传器响应式 */
@media (max-width: 768px) {
  .avatar-uploader {
    width: 120px !important;
    height: 120px !important;
  }

  .avatar-uploader-icon {
    width: 120px !important;
    height: 120px !important;
    line-height: 120px !important;
    font-size: 24px !important;
  }

  .avatar {
    width: 120px !important;
    height: 120px !important;
  }
}

/* 表单标签在小屏幕上的优化 */
@media (max-width: 480px) {
  .responsive-dialog .el-form-item {
    display: flex;
    flex-direction: column;
  }

  .responsive-dialog .el-form-item__label {
    text-align: left;
    margin-bottom: 5px;
  }

  .responsive-dialog .el-form-item__content {
    margin-left: 0 !important;
  }
}
</style>